//
//  LoginViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/1.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistViewController.h"
#import "ResetPWDViewController.h"

@interface LoginViewController ()

/** 头视图 */
@property (nonatomic, strong) UIImageView * headerImageView;
/** 注册按钮 */
@property (nonatomic, strong) UIButton * registButton;
/** 手机图标 */
@property (nonatomic, strong) UIImageView * phoneImageView;
/** 密码图标 */
@property (nonatomic, strong) UIImageView * pwdImageView;
/** 手机号输入框 */
@property (nonatomic, strong) UITextField * phoneTextField;
/** 密码输入框 */
@property (nonatomic, strong) UITextField * pwdTextField;
/** 密码可见按钮 */
@property (nonatomic, strong) UIButton * pwdVisibleButton;
/** 忘记密码按钮 */
@property (nonatomic, strong) UIButton * forgetPwdButton;
/** 登录按钮 */
@property (nonatomic, strong) UIButton * loginButton;
/** 返回按钮 */
@property (nonatomic, strong) UIButton * backButton;

@end

@implementation LoginViewController

- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
        [_backButton setImage:ImageNamed(@"back") forState:UIControlStateNormal];
        _backButton.transform = CGAffineTransformMakeRotation(-M_PI_2);
        __weak typeof(self)weakSelf = self;
        [_backButton initWithBlock:^(id obj) {
            DLog(@"返回");
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        } for:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UIButton *)registButton{
    if (!_registButton) {
        _registButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(60)) / 2, CGRectGetMaxY(self.loginButton.frame) + HeightScale(15), WidthScale(60), HeightScale(44))];
        [_registButton setTitle:@"注  册" forState:UIControlStateNormal];
        [_registButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        _registButton.titleLabel.font = FONTSIZE(15);
        __weak typeof(self)weakSelf = self;
        [_registButton initWithBlock:^(id obj) {
            DLog(@"注册");
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                [weakSelf.delegate registPresent];
            }];
        } for:UIControlEventTouchUpInside];
    }
    return _registButton;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(238)) / 2, SCREEN_H - HeightScale(180), WidthScale(238), HeightScale(61))];
        [_loginButton setImage:ImageNamed(@"login_s") forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [_loginButton initWithBlock:^(id obj) {
            DLog(@"登录");
            [weakSelf login];
            
        } for:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIButton *)forgetPwdButton{
    if (!_forgetPwdButton) {
        _forgetPwdButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(100), CGRectGetMaxY(self.pwdTextField.frame) , WidthScale(80), HeightScale(44))];
        [_forgetPwdButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
        [_forgetPwdButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        _forgetPwdButton.titleLabel.font = FONTSIZE(15);
        [_forgetPwdButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        __weak typeof(self)weakSelf = self;
        [_forgetPwdButton initWithBlock:^(id obj) {
            DLog(@"忘记密码?");
            ResetPWDViewController *resetPWDVC = [[ResetPWDViewController alloc] init];
            [weakSelf presentViewController:resetPWDVC animated:YES completion:nil];
        } for:UIControlEventTouchUpInside];
    }
    return _forgetPwdButton;
}

- (UIButton *)pwdVisibleButton{
    if (!_pwdVisibleButton) {
        
        _pwdVisibleButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(120), self.pwdTextField.frame.origin.y, WidthScale(100), HeightScale(40))];
        [_pwdVisibleButton setTitle:@"显示" forState:UIControlStateNormal];
        _pwdVisibleButton.titleLabel.font = FONTSIZE(17);
        [_pwdVisibleButton setTitle:@"隐藏" forState:UIControlStateSelected];
        [_pwdVisibleButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        [_pwdVisibleButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        __weak typeof(self)weakSelf = self;
        [_pwdVisibleButton initWithBlock:^(UIButton * pwdVisibleButton) {
            pwdVisibleButton.selected = !pwdVisibleButton.selected;
            if (pwdVisibleButton.selected) {
                DLog(@"显示");
                weakSelf.pwdTextField.secureTextEntry = NO;
            } else {
                DLog(@"隐藏");
                weakSelf.pwdTextField.secureTextEntry = YES;
            }
        } for:UIControlEventTouchUpInside];
    }
    return _pwdVisibleButton;
}

- (UITextField *)pwdTextField{
    if (!_pwdTextField) {
        _pwdTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneTextField.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(30), self.phoneTextField.frame.size.width, self.phoneTextField.frame.size.height)];
        _pwdTextField.placeholder = @"登录密码";
        _pwdTextField.font = FONTSIZE(17);
        
        UIImageView *underLine = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(_pwdTextField.frame), SCREEN_W - WidthScale(40), 0.5)];
        underLine.image = ImageNamed(@"fengexian");
        _pwdTextField.secureTextEntry = YES;
        _pwdTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self.view addSubview:underLine];
    }
    return _pwdTextField;
}

-(UIImageView *)pwdImageView{
    if (!_pwdImageView) {
        _pwdImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.phoneImageView.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(40), WidthScale(14), HeightScale(16))];
        _pwdImageView.image = ImageNamed(@"lock-icon");
    }
    return _pwdImageView;
}

- (UITextField *)phoneTextField{
    if (!_phoneTextField) {
        _phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.phoneImageView.frame) + WidthScale(15), CGRectGetMaxY(self.headerImageView.frame) + HeightScale(40), SCREEN_W - WidthScale(180), HeightScale(40))];
        _phoneTextField.placeholder = @"输入手机号或身份证号";
        _phoneTextField.font = FONTSIZE(17);
        
        UIImageView *underLine = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), CGRectGetMaxY(_phoneTextField.frame), SCREEN_W - WidthScale(40), 0.5)];
        underLine.image = ImageNamed(@"fengexian");
//        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self.view addSubview:underLine];
    }
    return _phoneTextField;
}

- (UIImageView *)phoneImageView{
    if (!_phoneImageView) {
        _phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(40), CGRectGetMaxY(self.headerImageView.frame) + HeightScale(40) + HeightScale(10), WidthScale(11.5), HeightScale(18))];
        _phoneImageView.image = ImageNamed(@"number");
    }
    return _phoneImageView;
}

- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 2)];
        _headerImageView.image = ImageNamed(@"background");
        _headerImageView.userInteractionEnabled = YES;
    }
    return _headerImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    [self.view addSubview:self.headerImageView];
    [self.view addSubview:self.registButton];
    [self.view addSubview:self.phoneImageView];
    [self.view addSubview:self.phoneTextField];
    [self.view addSubview:self.pwdImageView];
    [self.view addSubview:self.pwdTextField];
    [self.view addSubview:self.pwdVisibleButton];
    [self.view addSubview:self.forgetPwdButton];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.backButton];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.1 animations:^{
        [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H - [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
    }];
    
    
    [Tool setNavigationBarType:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
    DLog(@"%s", __func__);
}


#pragma mark - data request

- (void)login{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.phoneTextField.text forKey:@"userCode"];
    [params setValue:self.pwdTextField.text forKey:@"pwd"];
    
    NSString *URL = [NSString stringWithFormat:KLoginURL, KHostAddress, self.phoneTextField.text, self.pwdTextField.text];
    
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        
        DLog(@"%@", responseObject);
        
        if ([[responseObject objectForKey:@"error"] integerValue] == 0 ) {
            
            [ZRProgressHUD showMsgWithoutView:@"登录成功"];
            
            self.pwdTextField.text = @"";
            
            [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:[responseObject objectForKey:@"data"]];
            
            //字典序列化并存储到NSUserDefaults
            NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:[responseObject objectForKey:@"data"]];
            
            [[NSUserDefaults standardUserDefaults] setObject:userData forKey:@"user"];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        } else {
            NSString *errorMess = [responseObject objectForKey:@"data"];
            if (errorMess || ![errorMess isEqualToString:@""]) {
                [ZRProgressHUD showMsgWithoutView:errorMess];
            }else{
                [ZRProgressHUD showMsgWithoutView:@"登录失败, 请检查手机号和密码"];
            }
        }

    } failure:^(NSError *error) {
        
        [ZRProgressHUD showMsgWithoutView:@"登录失败, 请检查手机号和密码"];
        DLog(@"登录失败 %@", error);
        
    }];
}


@end
